package com.smssalama.storage.contact;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import javax.microedition.rms.RecordComparator;

import com.smssalama.storage.framework.Storable;

/**
 * An SMS Salama contact
 * 
 * @author Arnold P. Minde
 */
public class Contact extends Storable {
	public static final Object COMPARE_PHONE_NUMBER = new Object();
	public static final Object COMPARE_CONTACT_NAME = new Object();

	private String phoneNumber;
	private String contactName;
	private String sharedKey;
	private String email;
	private String note;

	public String getPhoneNumber() {
		return this.phoneNumber;
	}

	public String getSharedKey() {
		return this.sharedKey;
	}

	public void setSharedKey(String sharedKey) {
		this.sharedKey = sharedKey;
	}

	public String getEmail() {
		return this.email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getNote() {
		return this.note;
	}

	public void setNote(String note) {
		this.note = note;
	}

	public void setPhoneNumber(String phoneNumber) {
		this.phoneNumber = phoneNumber;
	}

	public void setContactName(String contactName) {
		this.contactName = contactName;
	}

	public String getContactName() {
		return this.contactName;
	}

	protected void store(DataOutputStream stream) throws IOException {
		stream.writeUTF(this.phoneNumber != null ? this.phoneNumber : "");
		stream.writeUTF(this.contactName != null ? this.contactName : "");
		stream.writeUTF(this.sharedKey != null ? this.sharedKey : "");
		stream.writeUTF(this.email != null ? this.email : "");
		stream.writeUTF(this.note != null ? this.note : "");
	}

	protected void load(DataInputStream stream) throws IOException {
		this.phoneNumber = stream.readUTF();
		this.contactName = stream.readUTF();
		this.sharedKey = stream.readUTF();
		this.email = stream.readUTF();
		this.note = stream.readUTF();
	}

	public static Object getComparatorCriteria(int[] compareFields) {
		return compareFields;
	}

	public int compareTo(Storable o) {
		return compareTo(o, Contact.COMPARE_CONTACT_NAME);
	}

	public int compareTo(Storable o, Object criteria) {
		if (!(o instanceof Contact)) {
			return RecordComparator.EQUIVALENT;
		}
		Contact c = (Contact) o;
		if (criteria == Contact.COMPARE_PHONE_NUMBER) {
			return (c.getPhoneNumber() != null ? c.getPhoneNumber() : "")
					.compareTo(getPhoneNumber() != null ? getPhoneNumber() : "");
		} else if (criteria == Contact.COMPARE_CONTACT_NAME) {
			//return (c.getContactName() != null ? c.getContactName() : "")
					//.compareTo(getContactName() != null ? getContactName() : "");
			return (getContactName() != null ? getContactName() : "")
				.compareTo(c.getContactName() != null ? c.getContactName() : "");
		}
		return super.compareTo(o, criteria);
	}
}
